package com.hjj.springboot.service.aop;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.hjj.springboot.config.SystemLogs;
import com.hjj.springboot.entity.Admin;
import com.hjj.springboot.entity.Logs;
import com.hjj.springboot.service.ILogsService;
import com.hjj.springboot.util.IpUtils;
import com.hjj.springboot.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Component
@Aspect
public class LogsAspect {

    @Resource
    ILogsService logsService;

    @AfterReturning(pointcut = "@annotation(systemLogs)",returning = "jsonResult")
    public void recordLog(JoinPoint joinPoint, SystemLogs systemLogs, Object jsonResult){
//        获取登录用户信息
        Admin  loginAdmin = JwtUtils.getCurrentAdmin();
        if(loginAdmin == null){
            Object[] args = joinPoint.getArgs();
            if (ArrayUtil.isNotEmpty(args)) {
                loginAdmin = (Admin) args[0];
            }
        }
        if(loginAdmin == null){
            log.error("记录日志报错，未获取当前操作用户信息");
            return;
        }

        ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
//        获取IP信息
        String ipAddr = IpUtils.getIpAddr(request);
        Logs logs = new Logs();
        logs.setUser(loginAdmin.getUserName());
        logs.setType(systemLogs.type().getValue());
        logs.setOperation(systemLogs.operation());
        logs.setIp(ipAddr);
        logs.setTime(new Date());

        logsService.save(logs);

    }

}
